import React, { useEffect, useRef, useState } from "react";
import "@/tailwind-variables.less";

const imgs = [
  "./imgs/lazyLoad/1.webp",
  "./imgs/lazyLoad/2.webp",
  "./imgs/lazyLoad/3.webp",
  "./imgs/lazyLoad/4.webp",
  "./imgs/lazyLoad/5.webp",
  "./imgs/lazyLoad/6.webp",
  "./imgs/lazyLoad/7.webp",
  "./imgs/lazyLoad/8.webp",
  "./imgs/lazyLoad/9.webp",
  "./imgs/lazyLoad/10.webp",
  "./imgs/lazyLoad/11.webp",
  "./imgs/lazyLoad/12.webp",
];

const LazyImage = ({
  src,
  placeholder,
  alt,
}: {
  src: string;
  placeholder: string;
  alt: string;
}) => {
  const [imageSrc, setImageSrc] = useState(placeholder);
  const observer = useRef<any>(null);
  const imgRef = useRef(null);

  useEffect(() => {
    const img = imgRef.current;
    if (img) {
      // 创建IntersectionObserver实例
      observer.current = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              setImageSrc(src);
              observer.current.unobserve(img);
            }
          });
        },
        {
          rootMargin: "0px", // 根元素的外边距，再storybook中失效，正常情况下有效果
        }
      );
      observer.current.observe(img);
    }
    return () => {
      if (observer.current) {
        observer?.current?.discount?.();
      }
    };
  }, [src]);

  return <img className="rounded-md" src={imageSrc} alt={alt} ref={imgRef} />;
};
export const ImageLazyLoadAPI: React.FC = () => {
  return (
    <div className="flex justify-center flex-col items-center">
      <h1 className="text-2xl font-bold">图片懒加载</h1>
      <div className="mt-2 max-w-[1024px] flex gap-2 flex-col">
        {imgs.map((img, index) => {
          return (
            <LazyImage
              key={index}
              src={img}
              placeholder={"./imgs/lazyLoad/loading.gif"}
              alt=""
            />
          );
        })}
      </div>
    </div>
  );
};
